package top.codedance.iotp.server.net.handle;

import com.alibaba.fastjson.JSONObject;
import top.codedance.iotp.common.entity.CommonEntity;
import top.codedance.iotp.server.ServerApplication;
import top.codedance.iotp.server.net.handle.configuration.ClientHandlerConfig;
import cd.io.netty.channel.ChannelHandlerContext;
import cd.io.netty.channel.SimpleChannelInboundHandler;
import top.codedance.iotp.server.net.handle.configuration.WsRouteConfig;
import org.apache.log4j.Logger;

import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.Set;

public class AsyncClientCommonHandler extends SimpleChannelInboundHandler<CommonEntity> {
    private static Logger logger = ServerApplication.getLogger(AsyncClientCommonHandler.class);

    protected void messageReceived(final ChannelHandlerContext channelHandlerContext, CommonEntity commonEntity) throws Exception {
        if(ClientHandlerConfig.asyncCmds.contains(commonEntity.getCommand())) {
            String body = new String(commonEntity.getBody(), StandardCharsets.UTF_8);
            final JSONObject params = JSONObject.parseObject(body);
            Map<Short, WsReceiveHandler> wsReceiveHandlers = WsRouteConfig.getWsReceiveHandlers();
            Set<Map.Entry<Short, WsReceiveHandler>> entries = wsReceiveHandlers.entrySet();
            for (Map.Entry<Short, WsReceiveHandler> entry : entries){
                if(entry.getKey() == commonEntity.getCommand()){
                    entry.getValue().receive(params.getString("deviceId"), params.getString("clientId"), params.getInteger("instance"), params.getString("data"));
                    break;
                }
            }
            logger.debug("ASYNC_COMMAND_RECEIVE: Command: " + commonEntity.getCommand());
        }else{
            channelHandlerContext.fireChannelRead(commonEntity); //向后传递
        }
    }
}
